package com.simteek.testspringdata.controller;

import com.simteek.testspringdata.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public Map findAll() {
        Map map = new HashMap();
        List list = userService.findAll();
        map.put("result", list);
        return map;
    }

    @RequestMapping(value = "/{_id}", method = RequestMethod.GET)
    public Map findById(@PathVariable("_id") String _id) {
        Map map = new HashMap();
        Object object = userService.findBy("_id", _id);
        map.put("result", object);
        return map;
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public Map save(Integer age, String firstName, String lastName) {
        Map map = new HashMap();
        try {
            userService.save(age, firstName, lastName);
            map.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", false);
        }
        return map;
    }

    @RequestMapping(value = "/{_id}", method = RequestMethod.PUT)
    public Map update(@PathVariable("_id") String _id, Integer age, String firstName, String lastName) {
        Map map = new HashMap();
        try {
            userService.update(_id, age, firstName, lastName);
            map.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", false);
        }
        return map;
    }

    @RequestMapping(value = "/{_id}", method = RequestMethod.DELETE)
    public Map deleteById(@PathVariable("_id") String _id) {
        Map map = new HashMap();
        userService.deleteById(_id);
        map.put("result", true);
        return map;
    }

}
